package com.boarsoft.boar.app.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.app.AppFileBiz;
import com.boarsoft.boar.entity.AppFile;
import com.boarsoft.boar.entity.FileInfo;
import com.boarsoft.boar.file.FileBiz;
import com.boarsoft.boar.service.FileService;
import com.boarsoft.common.dao.PagedResult;

@RestController
@RequestMapping("/app/file")
public class AppFileAction {
	@Autowired
	private AppFileBiz appFileBiz;
	@Autowired
	private FileBiz fileBiz;
	@Autowired
	private FileService fileSvc;

	/**
	 * 将多个文件与一个应用绑定，表示此应用会用到这些文件
	 * 
	 * @param appId
	 * @param fileIds
	 * @return
	 */
	@RequestMapping("/add.do")
	//@Authorized(code = "app.file.add")
	public ReplyInfo<Object> bind(String appId, String fileIds) {
		appFileBiz.add(appId, fileIds);
		return ReplyInfo.SUCCESS;
	}

	/**
	 * 根据appId查询返回AppId【已关联的】所有File_Info的集合 表file_info和表app_file的关联查询
	 * 
	 * @return
	 */
	@RequestMapping("/list.do")
//	@Authorized(code = "app.file.list")
	public ReplyInfo<Object> list(String appId, String key, String orderBy, int pageNo, int pageSize) {
		PagedResult<AppFile> pr = appFileBiz.list(appId, key, orderBy, pageNo, pageSize);
		return new ReplyInfo<>(true, pr);
	}

	@RequestMapping("/delete.do")
//	@Authorized(code = "app.file.delete")
	public ReplyInfo<Object> delete(String id, String env, String group) {
		AppFile af = appFileBiz.delete(id);
		FileInfo f = fileBiz.get(af.getFileId());
		// 如果文件专属于此应用，则删除文件信息
		if (f.getAppId().equals(af.getAppId())) {
			// TODO 先删除文件
			fileSvc.delete(f.getId(), env, group);
			// 再删除文件信息，并级联删除FileVersion和AppInstFile
			fileBiz.delete(f.getId());
		}
		return ReplyInfo.SUCCESS;
	}
}